package com.school.gmz.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.gmz.common.Result;
import com.school.gmz.entity.SecHand;
import com.school.gmz.mapper.SecHandMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/sechand")
@Api(tags = "二手市场管理") // 定义API的分类
public class SecHandController {
    @Resource
    SecHandMapper sechandMapper;

    // 添加二手商品
    @PostMapping
    @ApiOperation(value = "添加二手商品", notes = "创建一个新的二手商品记录")
    public Result<?> save(@RequestBody SecHand sechand){
        sechandMapper.insert(sechand);
        return Result.success();
    }

    // 更新二手商品
    @PutMapping
    @ApiOperation(value = "更新二手商品", notes = "根据ID更新二手商品记录")
    public Result<?> update(@RequestBody SecHand sechand){
        sechandMapper.updateById(sechand);
        return Result.success();
    }

    // 删除二手商品
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除二手商品", notes = "根据ID删除二手商品记录")
    public Result<?> delete(@ApiParam(value = "二手商品ID", required = true) @PathVariable Long id){
        sechandMapper.deleteById(id);
        return Result.success();
    }

    // 查询二手商品
    @GetMapping
    @ApiOperation(value = "查询二手商品", notes = "支持名字和价格查询")
    public Result<?> findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam(value = "名字", defaultValue = "") @RequestParam(defaultValue = "") String name,
            @ApiParam(value = "价格", defaultValue = "") @RequestParam(defaultValue = "") String money){
        LambdaQueryWrapper<SecHand> wrapper = Wrappers.<SecHand>lambdaQuery();
        if (StrUtil.isNotBlank(name)){
            wrapper.like(SecHand::getName, name);
        }
        if (StrUtil.isNotBlank(money)){
            wrapper.eq(SecHand::getMoney, money);
        }
        Page<SecHand> secHandPage = sechandMapper.selectPage(new Page<>(pageNum, pageSize), wrapper); // 默认分页参数
        return Result.success(secHandPage);
    }

    // 根据ID查询二手商品
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询二手商品", notes = "根据二手商品ID查询二手商品记录")
    public Result<?> findById(@ApiParam(value = "二手商品ID", required = true) @PathVariable Long id){
        SecHand secHand = sechandMapper.selectById(id);
        if (secHand != null) {
            return Result.success(secHand);
        } else {
            return Result.failure("二手商品不存在");
        }
    }
}